package com.wangwei.jvm.classloader;



import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

public class T006_MSBClassLoader extends ClassLoader {


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        File f = new File("D:/work/dac/temp/class/Hello.class");
        try (FileInputStream fis = new FileInputStream(f);
             ByteArrayOutputStream ba = new ByteArrayOutputStream()){
            int b = 0;
            while ((b=fis.read()) !=-1) {
                ba.write(b);
            }
            byte[] bytes = ba.toByteArray();
            return defineClass(name, bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.findClass(name); //throws ClassNotFoundException
    }

    public static void main(String[] args) throws Exception {
        ClassLoader l = new T006_MSBClassLoader();
        Class clazz = l.loadClass("com.wangwei.jvm.Hello");
        Class clazz1 = l.loadClass("com.wangwei.jvm.Hello");

        System.out.println(clazz == clazz1);

        Object h = clazz.newInstance();
        h.toString();
        System.out.println("h:"+h.getClass().getClassLoader());
        System.out.println(l.getClass().getClassLoader());
        System.out.println(l.getParent());

        System.out.println(getSystemClassLoader());
    }

}
